package com.tpsix.security.saas;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class TenantContextFilter extends OncePerRequestFilter {

    private static final String TENANT_ID_KEY = "TENANT_ID";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 从请求头中, 获取租户id
        String tenantId = request.getHeader(TENANT_ID_KEY);

        // 告诉租户上下文当前的租户id
        if (StringUtils.isNotBlank(tenantId)) {
            TenantContextHolder.setTenantId(Long.valueOf(tenantId));
        } else {
            TenantContextHolder.setTenantId(3L);
        }
        chain.doFilter(request, response);
    }

}
